package cn.tedu.lbs.basic.web.service;

import cn.tedu.lbs.basic.web.repository.AdminRepository;
import cn.tedu.lbs.basic.web.util.AuthenticationContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.param.AdminParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminService {
    @Autowired
    private AdminRepository adminRepository;

    public AdminVO detail(Integer adminId) {
        AdminPO po = adminRepository.getById(adminId);
        AdminVO vo= new AdminVO();
        BeanUtils.copyProperties(po,vo);
        return vo;
    }

    public PageResult<AdminVO> pageList(AdminQuery query) {
        //1.如果使用分页查询 开启分页 查询列表 封装pageInfo 不在编写相似的代码
        PageResult<AdminVO> voPage=new PageResult<>(10,1);
        voPage.setTotal(100L);
        //2.list查询 查询其实是所有
        List<AdminPO> pos = adminRepository.list();
        //3.转化
        voPage.setObjects(pos.stream().map(po->{
            AdminVO vo=new AdminVO();
            BeanUtils.copyProperties(po,vo);
            return vo;
        }).collect(Collectors.toList()));
        return voPage;
    }

    public void save(AdminParam adminParam) throws BusinessException {
        //1.新增权限 只有ADMIN角色可以新增后台账号
        checkRole(Roles.ADMIN);
        //2.保证账号使用的手机号 幂等的,如果不能保证后台登录 就会有问题
        saveAdmin(adminParam);
    }

    private void saveAdmin(AdminParam adminParam) throws BusinessException {
        //1.查询入参电话号码是否存在 select count(0) from lbs_admin where account_phone=?
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("account_phone",adminParam.getAccountPhone());
        long count = adminRepository.count(queryWrapper);
        Asserts.isTrue(count>0,new BusinessException("-2","手机号重复"));
        //2.不存在 则转化po新增
        AdminPO poParam=new AdminPO();
        BeanUtils.copyProperties(adminParam,poParam);
        //补充 其他参数条件 create_time
        poParam.setCreateTime(new Date());
        adminRepository.save(poParam);
    }

    private void checkRole(Roles roles) throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        //判断角色是否和指定角色一致
        Asserts.isTrue(userPrinciple.getRole()!=roles,new BusinessException("-2","用户权限不足"));
    }
}
